<template>
  <div
    v-loading="loading"
    style="display: flex; flex-direction: column; flex: 1"
    element-loading-text="加载中..."
  >
    <div class="header flex-justify-between">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addRule"> 新建分配规则 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length === 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search flex-align-center">
        <el-input
          v-model="name"
          placeholder="名称搜索"
          class="input-with mr5"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <!-- 列表表格 -->
    <div class="table-list">
      <el-table
        border
        stripe
        resizable
        :data="tableData"
        @selection-change="handleChange"
        ref="tableDom"
        height="100%"
        style="position: absolute"
      >
        <el-table-column show-overflow-tooltip type="selection" width="40" fixed="left" />
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
        />
        <el-table-column show-overflow-tooltip prop="name" label="规则名称" min-width="200" />
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="!scope.row.status">启用</HStatus>
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="moduleName" label="模块名称" width="250" />
        <el-table-column show-overflow-tooltip prop="condition" label="规则条件" width="150" />
        <el-table-column show-overflow-tooltip prop="type" label="分配方式" width="80">
          <template #default="scope">
            <span v-if="scope.row.type == 1">平均分配</span>
            <span v-if="scope.row.type == 2">随机分配</span>
            <span v-if="scope.row.type == 3">熟客优先</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="empType" label="人员类型" width="80">
          <template #default="scope">
            <span v-if="scope.row.empType == 1">客服</span>
            <span v-if="scope.row.empType == 2">客服组</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="emp" label="分配人员" width="250" />
        <el-table-column show-overflow-tooltip prop="weight" label="优先级" width="70" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="150" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="150" />
        <el-table-column label="操作" width="60" fixed="right">
          <template #default="scope">
            <HLink @click="editRule(scope.row.id)">详细</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="footer flex-justify-end">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  规则弹窗 -->
    <HModal v-model="addDialog" width="500">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ dialogTitle }}</h3>
        </div>
      </template>
      <div class="rule-dialog">
        <div v-loading="dialogLoading">
          <div class="form-text">
            <el-form
              label-width="85"
              ref="formRef"
              :rules="rules"
              :model="form"
              @validate="handleFormValidate"
            >
              <el-form-item label="规则名称" :style="getFormItemStyle['name']" prop="name">
                <el-input v-model="form.name" clearable placeholder="请输入名称" />
              </el-form-item>
              <div style="display: flex; margin-bottom: 4px">
                <p style="width: 85px; opacity: 0">占位</p>
                <p>需满足以下所有条件，自动分配规则才会生效</p>
              </div>
              <div class="cards">
                <div v-for="(item, i) in form.conditionVos" :key="i" class="card">
                  <div class="icons">
                    <el-icon size="16" color="#007cff" @click="addCondition">
                      <CirclePlus />
                    </el-icon>
                    <el-icon color="#f56c6c" size="16" @click="deleteCondition(i, item.id)">
                      <RemoveFilled />
                    </el-icon>
                  </div>
                  <el-form-item :label="`条件${i + 1}`" class="item-cond" label-width="51">
                    <div class="item">
                      <el-form-item
                        style="margin-bottom: 15px"
                        label="规则条件"
                        :prop="`conditionVos[${i}][type]`"
                        :rules="rules.type"
                      >
                        <el-select
                          v-model="item.type"
                          class="width-select"
                          filterable
                          clearable
                          placeholder="请选择条件"
                        >
                          <el-option label="品牌" :value="1" />
                          <el-option label="商品分类" :value="2" />
                          <el-option label="客户区域" :value="3" />
                          <!-- <el-option label="工单模块" :value="4" /> -->
                        </el-select>
                      </el-form-item>
                      <el-form-item label="规则内容">
                        <el-select
                          v-if="!item.type"
                          class="width-select"
                          placeholder="请先选择条件"
                        >
                        </el-select>
                        <el-select
                          v-if="item.type == 1"
                          v-model="item.conditionChildVos[0].valId"
                          class="width-select"
                          placeholder="请选择品牌"
                          filterable
                          clearable
                          reserve-keyword
                          remote-show-suffix
                          :loading="brandLoad"
                          :filter-method="searchBrandSelect"
                        >
                          <el-option
                            v-for="item in brandOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>
                        <el-select
                          v-if="item.type == 2"
                          v-model="item.conditionChildVos[0].valId"
                          class="width-select"
                          placeholder="请选择分类"
                          filterable
                          clearable
                          reserve-keyword
                          remote-show-suffix
                          :loading="typeLoad"
                          :filter-method="searchTypeSelect"
                        >
                          <el-option
                            v-for="item in typeOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>
                        <SingleAddress
                          v-if="item.type == 3"
                          ref="addrsDom"
                          class="width-select"
                          :address="addrsData"
                          @value-change="handleAddressUpdate"
                        />
                        <el-select
                          v-if="item.type == 4"
                          v-model="item.conditionChildVos[0].valId"
                          class="width-select"
                          placeholder="请选择工单模块"
                          filterable
                          clearable
                          reserve-keyword
                          remote-show-suffix
                          :loading="moduleLoad"
                          :filter-method="searchModuleSelect"
                        >
                          <el-option
                            v-for="item in moduleOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                    </div>
                  </el-form-item>
                </div>
              </div>
              <div class="tips flex-align-center">满足以上条件，则执行以下分配策略</div>
              <el-form-item label="分配方式" class="form_radio_item" style="margin-bottom: 14px">
                <el-radio-group v-model="form.type" class="three_radio">
                  <el-radio :value="1">
                    <span class="bg_text">平均分配</span>
                  </el-radio>
                  <el-radio :value="2">
                    <span class="bg_text">随机分配</span>
                  </el-radio>
                  <el-radio :value="3">
                    <span class="bg_text">熟客优先</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="人员类型" class="form_radio_item" style="margin-bottom: 14px">
                <el-radio-group v-model="form.empType" class="three_radio" @change="typeChange">
                  <el-radio :value="1">
                    <span class="bg_text">客服</span>
                  </el-radio>
                  <el-radio :value="2">
                    <span class="bg_text">客服组</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="客服组人员" style="margin-bottom: 12px" v-if="form.empType == 2">
                <el-select
                  v-model="form.serviceIds"
                  class="item-select"
                  placeholder="请选择客服组人员"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="customLoad"
                  :filter-method="searchTeamSelect"
                >
                  <el-option
                    v-for="item in teamOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="客服人员" style="margin-bottom: 12px" v-if="form.empType == 1">
                <el-select
                  v-model="form.serviceIds"
                  class="item-select"
                  placeholder="请选择客服人员"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="customLoad"
                  :filter-method="searchCustomSelect"
                >
                  <el-option
                    v-for="item in customOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="优先级" style="margin-bottom: 12px">
                <el-input v-model="form.weight" clearable placeholder="不填写则系统默认排序" />
              </el-form-item>
              <el-form-item label="规则状态" class="form_radio_item">
                <el-radio-group v-model="form.status" class="three_radio">
                  <el-radio :value="false">
                    <span class="bg_text">启用</span>
                  </el-radio>
                  <el-radio :value="true">
                    <span class="bg_text">禁用</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <template #footerLeft>
        <HPlainBgButton
          is-modal
          type="error"
          v-show="dialogTitle == '编辑规则'"
          @click="changeAll(4)"
          >删除</HPlainBgButton
        >
      </template>

      <template #footerRight>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, markRaw } from 'vue'
  import {
    Search,
    Warning,
    Delete,
    RemoveFilled,
    CirclePlus,
    CircleCheck,
    ArrowDown,
  } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { workModulePageSelect, workTeamPageSelect } from '@/api/order'
  import {
    clientGetList,
    clientSave,
    clientDisable,
    clientDelete,
    clientGetDetail,
  } from '@/api/basic'
  import { empPageSelecct } from '@/api/organize'
  import { brandPageSelect, typePageSelect } from '@/api/goodsInfo'
  import _ from 'lodash'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, getFormItemStyle, resetFormValidateResult } = useFormValidateService([
    { name: 'name', isSelect: false },
    { name: 'type', isSelect: false },
  ])

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addDialog.value = false
    resetFormValidateResult()
  }

  const name = ref('') // 名称
  const tableData = ref([]) // 列表数据
  const tableDom = ref() // 列表dom
  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目
  const loading = ref(false)
  const addDialog = ref(false)
  const dialogTitle = ref('')
  const dialogLoading = ref(false)
  const formRef = ref<FormInstance>() // 表单元素

  // 表单数据
  const form = reactive({
    conditionVos: [
      {
        id: null,
        conditionChildVos: [
          {
            area: '',
            city: '',
            province: '',
            town: '',
            valId: '',
          },
        ],
        type: null,
      },
    ],
    delConditionIds: [],
    empType: 1,
    id: null,
    name: '',
    serviceIds: [],
    status: false,
    type: 1,
    weight: 0,
  })

  // 验证规则
  const rules = ref({
    name: [{ required: true, message: '请输入规则名称', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '请选择规则条件', trigger: ['blur', 'change'] }],
  })

  // 工单模块下拉相关
  const moduleOptions = ref([])
  const moduleLoad = ref(false)
  const moduleVal = ref('')

  // 客服 客服组下拉相关
  const customOptions = ref([])
  const teamOptions = ref([])
  const customLoad = ref(false)
  const customVal = ref('')
  const teamVal = ref('')

  // 商品品牌下拉相关
  const brandOptions = ref([])
  const brandLoad = ref(false)
  const brandVal = ref('')

  // 商品分类下拉相关
  const typeOptions = ref([])
  const typeLoad = ref(false)
  const typeVal = ref('')

  const addrsDom = ref()
  const addrsData = ref()

  // 列表序号
  const indexMethod = (index: number) => {
    return index + 1
  }

  // 获取工单模块下拉
  const getModuleOptions = async (name: string) => {
    moduleLoad.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await workModulePageSelect(data)
    moduleOptions.value = res.data.data.rows
    moduleLoad.value = false
  }

  // 搜索工单模块下拉
  const searchModuleSelect = _.throttle((query: string) => {
    if (moduleVal.value !== query) {
      moduleVal.value = query
      getModuleOptions(moduleVal.value)
    }
  }, 500)

  // 获取商品品牌下拉
  const getBrandOptions = async (name: string) => {
    brandLoad.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await brandPageSelect(data)
    brandOptions.value = res.data.data.rows
    brandLoad.value = false
  }

  // 搜索商品品牌下拉
  const searchBrandSelect = _.throttle((query: string) => {
    if (brandVal.value !== query) {
      brandVal.value = query
      getBrandOptions(brandVal.value)
    }
  }, 500)

  // 获取商品分类下拉
  const getTypeOptions = async (name: string) => {
    typeLoad.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await typePageSelect(data)
    typeOptions.value = res.data.data.rows
    typeLoad.value = false
  }

  // 搜索商品分类下拉
  const searchTypeSelect = _.throttle((query: string) => {
    if (typeVal.value !== query) {
      typeVal.value = query
      getTypeOptions(query)
    }
  }, 500)

  // 获取客服人员下拉
  const getCustomOptions = async (name: string) => {
    customLoad.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await empPageSelecct(data)
    customOptions.value = res.data.data.rows
    customLoad.value = false
  }

  // 搜索客服人员下拉
  const searchCustomSelect = _.throttle((query: string) => {
    if (customVal.value !== query) {
      customVal.value = query
      getCustomOptions(customVal.value)
    }
  }, 500)

  // 获取客服组人员下拉
  const getTeamOptions = async (name: string) => {
    customLoad.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await workTeamPageSelect(data)
    teamOptions.value = res.data.data.rows
    customLoad.value = false
  }

  // 搜索客服组人员下拉
  const searchTeamSelect = _.throttle((query: string) => {
    if (teamVal.value !== query) {
      teamVal.value = query
      getTeamOptions(teamVal.value)
    }
  }, 500)

  // 人员类型变化时
  const typeChange = () => {
    form.serviceIds = []
  }

  // 添加条件
  const addCondition = () => {
    if (form.conditionVos.length == 4) {
      ElMessage({
        message: '最多添加4个条件！',
        type: 'warning',
        duration: 2000,
      })
      return
    }
    form.conditionVos.push({
      id: null,
      conditionChildVos: [
        {
          area: '',
          city: '',
          province: '',
          town: '',
          valId: '',
        },
      ],
      type: null,
    })
  }

  // 删除条件
  const deleteCondition = (i: number, id: string) => {
    if (form.conditionVos.length == 1) {
      ElMessage({
        message: '至于保留1个条件！',
        type: 'warning',
        duration: 2000,
      })
      return
    }
    form.conditionVos.splice(i, 1)
    if (id) {
      form.delConditionIds.push(id)
    }
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取分页数据
  const getPageData = () => {
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    await clientGetList(getPageData()).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  defineExpose({ getList })

  // 添加规则
  const addRule = () => {
    dialogTitle.value = '添加规则'
    addDialog.value = true
    getModuleOptions('')
    getBrandOptions('')
    getTypeOptions('')
    getCustomOptions('')
    getTeamOptions('')
    form.conditionVos = [
      {
        id: null,
        conditionChildVos: [
          {
            area: '',
            city: '',
            province: '',
            town: '',
            valId: '',
          },
        ],
        type: null,
      },
    ]
    form.delConditionIds = []
    form.empType = 1
    form.id = null
    form.name = ''
    form.serviceIds = []
    form.status = false
    form.type = 1
    form.weight = 0
  }

  // 编辑规则
  const editRule = async (id) => {
    dialogTitle.value = '编辑规则'
    addDialog.value = true
    dialogLoading.value = true
    getModuleOptions('')
    getBrandOptions('')
    getTypeOptions('')
    getCustomOptions('')
    getTeamOptions('')
    form.delConditionIds = []
    await clientGetDetail(id).then((res) => {
      form.conditionVos = res.data.data.row.conditionVos
      form.conditionVos.forEach((item) => {
        if (item.conditionChildVos[0].valId == '0') {
          item.conditionChildVos[0].valId = ''
        }
      })
      res.data.data.row.conditionVos.forEach((item) => {
        if (item.type == 3) {
          addrsData.value = {
            province: item.conditionChildVos[0].province,
            city: item.conditionChildVos[0].city,
            area: item.conditionChildVos[0].area,
            town: item.conditionChildVos[0].town,
          }
        }
      })
      form.empType = res.data.data.row.empType
      form.id = res.data.data.row.id
      form.name = res.data.data.row.name
      form.serviceIds = res.data.data.row.serviceIds
      form.status = res.data.data.row.status
      form.type = res.data.data.row.type
      form.weight = res.data.data.row.weight
    })
    dialogLoading.value = false
  }

  // 保存方法
  const saveDataMethod = (method, data) => {
    dialogLoading.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        addDialog.value = false
        dialogLoading.value = false
        getList()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        dialogLoading.value = false
        return
      }
    })
  }

  // 地址
  const address = ref({
    province: '',
    area: '',
    city: '',
    town: '',
  })

  // 地址更新事件
  const handleAddressUpdate = (addr: {
    province: string
    area: string
    city: string
    town: string
  }) => {
    address.value.province = addr.province
    address.value.area = addr.area
    address.value.city = addr.city
    address.value.town = addr.town
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        if (addrsDom.value) {
          form.conditionVos.forEach((item, i) => {
            if (item.type == 3) {
              item.conditionChildVos[0].area = address.value.area
              item.conditionChildVos[0].city = address.value.city
              item.conditionChildVos[0].province = address.value.province
              item.conditionChildVos[0].town = address.value.town
            } else {
              item.conditionChildVos[0].area = ''
              item.conditionChildVos[0].city = ''
              item.conditionChildVos[0].province = ''
              item.conditionChildVos[0].town = ''
            }
          })
        }
        // 判断条件是否重复
        let isRepeat
        const newArr = form.conditionVos.map((item) => item.type)
        isRepeat = newArr.some((x, index, arr) => arr.findIndex((y) => y == x) != index)
        if (isRepeat) {
          ElMessage({
            message: '规则条件重复',
            type: 'warning',
            duration: 2000,
          })
          return
        }
        saveDataMethod(clientSave, form)
      }
    })
  }

  // 修改状态的方法
  const chnageMethod = (arr, type, method, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的规则`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的规则?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n) => {
    switch (n) {
      case 1:
        chnageMethod(selecttion.value, '启用', clientDisable, false, '')
        break
      case 2:
        chnageMethod(selecttion.value, '禁用', clientDisable, true, '')
        break
      case 3:
        chnageMethod(selecttion.value, '删除', clientDelete, 3, '')
        break
      case 4:
        chnageMethod([form.id], '删除', clientDelete, 3, 1)
        break
    }
  }
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
